import pandas as pd
from torqueSrc.tools.lambdaDecorator import LambdaDecorator
from common.config import torqueConfig as Config

import numpy as np
import os

@LambdaDecorator.formulate
def onlLambdaProcess(X):
    print('groupProcess 进行中................')
    return X

# 对UploadTorqCoef做一定的限定
def Limit_UploadTorqCoef(UploadTorqCoef):
    if UploadTorqCoef > (1+Config.torqCoef_AdjLimit):
        return (1+Config.torqCoef_AdjLimit)
    elif UploadTorqCoef < (1-Config.torqCoef_AdjLimit):
        return (1-Config.torqCoef_AdjLimit)
    return UploadTorqCoef

def torqCoefAdjProcess():
    # 读 hisLambdaOptProcess.csv 和 onlLambdaProcess.csv
    X_optLambda = pd.read_csv(Config.hisLambdaOptProcess)
    X_curLambda = pd.read_csv(Config.onlLambdaProcess)

    # 取两条曲线中 windSpeed_min中较大者，windSpeed_max中较小者，用来求这段的rotateSpeed差值平均值
    windSpeed_min = np.max([X_optLambda[Config.WindSpeed].min(), X_curLambda[Config.WindSpeed].min()])
    windSpeed_max = np.min([X_optLambda[Config.WindSpeed].max(), X_curLambda[Config.WindSpeed].max()])
    print("windSpeed_min: ", windSpeed_min)
    print("windSpeed_max: ", windSpeed_max)
    X_optLambda = X_optLambda[(X_optLambda[Config.WindSpeed] >= windSpeed_min) & (X_optLambda[Config.WindSpeed] <= windSpeed_max)]
    X_curLambda = X_curLambda[(X_curLambda[Config.WindSpeed] >= windSpeed_min) & (X_curLambda[Config.WindSpeed] <= windSpeed_max)]
    # print("X_optLambda: ", X_optLambda)
    # print("X_curLambda: ", X_curLambda)


    # 2022.6.8 找到了转矩系数调整与转速变化之间3次方关系，因此，不再需要指定转矩系数调整次数Config().coef_torqFacVsRotateDiff
    opt_rotateSpeed_mean = X_optLambda[Config.RotateSpeed].mean()
    cur_rotateSpeed_mean = X_curLambda[Config.RotateSpeed].mean()
    torqueCoefAdj_rate = (cur_rotateSpeed_mean / opt_rotateSpeed_mean) ** 3  # 转矩系数的调整率 大约 应是转速变化相对值的 3次方，可以将转速调回到最优
    # print("转矩系数调整率 (调整后/调整前)：", torqueCoefAdj_rate)


    '''
    写torqCoefAdjProcess.csv文件，文件只有一行记录，结构为：
    理论转矩系数定为“1”
    JustNowTorqCoef: 刚刚使用的转矩系数，新生成的文件的JustNowTorqCoef取前一个表的 UploadTorqCoef，无实际用途，可能显示图像会用到
    Adjust: 转矩系数需要调整的百分比（相对于 JustNowTorqCoef 值）
    UploadTorqCoef: 转矩系数调整之后的值（注意不要超出限制）
    1. 如果文件存在，读出数据，重点是读出 UploadTorqCoef, 计算新的 JustNowTorqCoef=UploadTorqCoef, UploadTorqCoef=JustNowTorqCoef * torqueCoefAdj_rate
    2. 如果文件不存在，用“1” 取代JustNowTorqCoef，计算 UploadTorqCoef=JustNowTorqCoef * torqueCoefAdj_rate
    3. 对UploadTorqCoef进行一定的限制
    4. 写文件
    '''
    # 1
    JustNowTorqCoef = 1
    if os.path.exists(Config.torqCoefAdjProcess):
        df = pd.read_csv(Config.torqCoefAdjProcess)
        JustNowTorqCoef = 1 if np.isnan(df['UploadTorqCoef'][0]) else df['UploadTorqCoef'][0]
    UploadTorqCoef = JustNowTorqCoef * torqueCoefAdj_rate

    # 3
    UploadTorqCoef = Limit_UploadTorqCoef(UploadTorqCoef)
    print("转矩系数调整率：", UploadTorqCoef)
    # 4
    df = pd.DataFrame(
            {'JustNowTorqCoef': [JustNowTorqCoef], 'AdjustRate': [torqueCoefAdj_rate],
             'UploadTorqCoef': [UploadTorqCoef]})
    df.to_csv(Config.torqCoefAdjProcess, index=False)


    #缺了一个写Attr的过程

if __name__ == '__main__':


    torqCoefAdjProcess()
